
package com.itcs.box.server.resolver;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.server.server.NettyChannelMap;
import com.itcs.box.util.BoxResUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

/**
 * 功能描述:
 * <验证通讯盒登录状态>
 *
 * @ClassName: BoxIdCheckTopicResolver
 * @Author: wanghui
 * @Date: 2019年05月17日 09:36:52
 *
 * @Copyright: 2019 Inc. All rights reserved. 注意: 本内容仅限于内部传阅,禁止外泄以及用于其他的商业目
 */
@Component
public class BoxIdCheckTopicResolver {

	public static String KEY_PREFIX = "boxid_check_";
	public final static String STATUS_正常 = "0";

	public final static String STATUS_测试中 = "1";
	public final static String STATUS_异常 = "9";

	private Log logger = LogFactory.getLog(getClass());

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public void check(String deviceId) {
		if (NettyChannelMap.get(deviceId) != null) {
			ValueOperations<String, String> opsValue = stringRedisTemplate.opsForValue();
			opsValue.set(KEY_PREFIX + deviceId, STATUS_测试中);

			logger.info(MessageFormat.format(
					"验证通讯盒 {0} 登录,在当前服务登录,发送心跳包检测已登录连接是否正常", deviceId));

			ByteBuf byteBuf = Unpooled.wrappedBuffer(
					JSON.toJSONString(BoxResUtils.build1002(deviceId)).getBytes(BoxConstants.CHARSET_UTF8));
			NettyChannelMap.get(deviceId).writeAndFlush(byteBuf);
			// 循环20次检测旧连接是否断开
			for (int i = 0; i < 20; i++) {
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}
				if (NettyChannelMap.isNotExists(deviceId)) {
					logger.info(MessageFormat.format(
							"验证通讯盒 {0} 心跳,连接状态异常，已断开，允许新连接登录", deviceId));
					opsValue.set(KEY_PREFIX + deviceId, STATUS_异常);
					return;
				}
			}

			opsValue.set(KEY_PREFIX + deviceId, STATUS_正常);
			logger.info(MessageFormat.format("验证通讯盒 {0} 心跳,连接状态正常", deviceId));
		} else {
			logger.info(MessageFormat.format("验证通讯盒 {0} 登录,未在当前服务登录", deviceId));
		}
	}
}
